/*
   Copyright (c) 2010 Bryce Alcock

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.com

 */
package com.ecocrypt.proxy.forwarder.gui;

import com.ecocrypt.network.utils.SizeOfUtil;
import com.ecocrypt.proxy.forwarder.ClientServiceRequest;
import com.ecocrypt.proxy.forwarder.Forwarder;
import com.ecocrypt.proxy.forwarder.transfer.ForwarderListener;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author bryce
 */
public class ForwardPanelTableModel extends AbstractTableModel implements ForwarderListener {

    private long totalSize = 0;
    private long completedSize = 0;
    Forwarder forwarder;
    ArrayList<ClientServiceRequest> currentReqs = new ArrayList<ClientServiceRequest>();

    // NOTE:  Potential High Memory Usage.
    //        Because this is a bounded queue, it could consume high memory if the bounds
    //        are too large.
    ArrayBlockingQueue<ClientServiceRequest> completed = new ArrayBlockingQueue<ClientServiceRequest>(3000);
    ClientServiceRequest[] completedOrdered = new ClientServiceRequest[0];

    boolean isActive = true;
    boolean isFrozen = false;

    public ForwardPanelTableModel(Forwarder f) {
        f.register(this);
        forwarder = f;
    }

    public long getTotalSize() {
        return totalSize;
    }

    public long getCompletedSize() {
        return completedSize;
    }

    public int getRowCount() {
        if (isActive) {
            return currentReqs.size();
        }
        int size = completed.size();
        if (completedOrdered.length < size) {
            completedOrdered = new ClientServiceRequest[size];
        }
        completed.toArray(completedOrdered);
        return completed.size();
    }

    public int getColumnCount() {
        return 11;
    }

    public ClientServiceRequest getItemAt(int rowIndex) {
        ClientServiceRequest csr = null;
        if (isActive) {
            csr = currentReqs.get(rowIndex);
        } else {
            csr = completedOrdered[rowIndex];
        }
        return csr;

    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        try {

            ClientServiceRequest csr = null;
            if (isActive) {
                csr = currentReqs.get(rowIndex);
            } else {
                csr = completedOrdered[rowIndex];
            }
            Object[] oa = csr.currentState();
            switch (columnIndex) {

                case 0:
                    return oa[0];// service Id
                case 1:
                    return oa[1];// durration
                case 2:
                    return new Timestamp((Long) oa[2]);// start Time
                case 3:
                    return oa[3];// bytes from cleint
                case 4:
                    return oa[4];//  bytes sent to engine
                case 5:
                    return oa[5];//  bytes from engine
                case 6:
                    return oa[6];//  bytes to cleint
                case 7:
                    return oa[7];//new Integer(-1);//"Port Eng";
                case 8:
                    return oa[8];//new Integer(-1);//"Port Clnt";
                case 9:
                    return new Timestamp((Long)oa[9]);//new Timestamp(0);//"Clnt In Tm";
                case 10:
                    return new Timestamp((Long)oa[10]);//new Timestamp(0);//"Eng In Tm";


            }
        } catch (Exception e) {
            switch (columnIndex) {

                case 0:
                    return new Integer(-1);// service Id
                case 1:
                    return new Long(-1);// durration
                case 2:
                    return new Timestamp(0);// start Time
                case 3:
                    return new Integer(-1);// bytes from cleint
                case 4:
                    return new Integer(-1);//  bytes sent to engine
                case 5:
                    return new Integer(-1);//  bytes from engine
                case 6:
                    return new Integer(-1);//  bytes to cleint
                case 7:
                    return new Integer(-1);//"Port Eng";
                case 8:
                    return new Integer(-1);//"Port Clnt";
                case 9:
                    return new Timestamp(0);//"Clnt In Tm";
                case 10:
                    return new Timestamp(0);//"Eng In Tm";
            }
        }
        return -1;
    }

    @Override
    public String getColumnName(int column) {
        switch (column) {

            case 0:
                return "service Id";
            case 1:
                return "durration";
            case 2:
                return "start Time";
            case 3:
                return "Clnt IN ";
            case 4:
                return "Eng OUT ";
            case 5:
                return "Eng IN";
            case 6:
                return "Clnt OUT";
            case 7:
                return "Port Eng";
            case 8:
                return "Port Clnt";
            case 9:
                return "Clnt In Tm";
            case 10:
                return "Eng In Tm";
        }
        return "Not Found";

    }

    @Override
    public Class<?> getColumnClass(int column) {
        switch (column) {

            case 0:
                return Integer.class;
            case 1:
                return Long.class;
            case 2:
                return Date.class;
            case 3:
                return Integer.class;
            case 4:
                return Integer.class;
            case 5:
                return Integer.class;
            case 6:
                return Integer.class;
            case 7:
                return Integer.class;
            case 8:
                return Integer.class;
            case 9:
                return Date.class;
            case 10:
                return Date.class;
        }
        return Object.class;

    }

    // Only used to make the initial sizing of the columns.
    // This is the maximum size for each of these fields.
    //--------------------------------------------------------------------------
    // Additional Licence Related oracle:  CODE MODIFIED BY 47906 PROXY.
    /*
        * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
        *
        * Redistribution and use in source and binary forms, with or without
        * modification, are permitted provided that the following conditions
        * are met:
        *
        *   - Redistributions of source code must retain the above copyright
        *     notice, this list of conditions and the following disclaimer.
        *
        *   - Redistributions in binary form must reproduce the above copyright
        *     notice, this list of conditions and the following disclaimer in the
        *     documentation and/or other materials provided with the distribution.
        *
        *   - Neither the name of Oracle or the names of its
        *     contributors may be used to endorse or promote products derived
        *     from this software without specific prior written permission.
        *
        * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
        * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
        * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
        * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
        * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
        * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
        * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
        * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
        * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
        * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        */

     public final Object[] longValues = {"9999",
                                         999999,
                                         new Date(),
                                         "999,999",
                                         "999,999",
                                         "999,999",
                                         "999,999",
                                         "64000",
                                         "64000",
                                         new Date(),
                                         new Date()};
   //  END ORACLE CODE MODIFIED.
   //--------------------------------------------------------------------------

    public void connectionAdded(Forwarder source) {
        //  Update the Active Connection Table Data.
        //  Fire a table rows changed event, if we are in the correct mode.
        currentReqs = source.getCurrentRequests();
        if (!isFrozen) {
            fireTableDataChanged();
        }

    }

    public void connectionRemoved(Forwarder source, ClientServiceRequest csr) {
        // Update the Inactive Connection Table Data.
        // fire a table rows changed event, if we are in the correct mode.
        currentReqs = source.getCurrentRequests();
        if (!completed.offer(csr)) {
            ClientServiceRequest rc = completed.remove();
            long sizeRc = SizeOfUtil.sizeof(rc);
            totalSize -= sizeRc;
            completedSize -= sizeRc;
            // TODO:  Technicall this requires retry with recursion...
            //        In theory the offer below could fail, and if so shoud
            //        have another element removed, and an offer tried again.
            if (completed.offer(csr)) {
                long sizeOffer = SizeOfUtil.sizeof(csr);
                totalSize += sizeOffer;
                completedSize += sizeOffer;
            }
        } else {
            long sizeOffer = SizeOfUtil.sizeof(csr);
            totalSize += sizeOffer;
            completedSize += sizeOffer;
        }

        if (!isFrozen) {
            fireTableDataChanged();
        }
    }

    public void connectionDataChanged(Forwarder source, ClientServiceRequest csr) {
        // Find the table row,
        // update the record.
        // if we are in the correct mode and the record existed then,
        //   fire a row data changed event.
        currentReqs = source.getCurrentRequests();
        if (!isFrozen) {
            fireTableDataChanged();
        }

    }

    public void forwarderDynamicStateChanged(Forwarder source) {
	//System.out.println("ForwarderDynamicStateChanged");
        currentReqs = source.getCurrentRequests();
        if (!isFrozen) {
            fireTableDataChanged();
        }
    }
}
